package com.zb.frame.base.utils;

import com.zb.frame.base.upgrade.utils.DBHelper;
import com.zb.frame.base.utils.encrypt.DESUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.util.ArrayList;

@Component
public class DBUtil {

    private static Logger logger = LoggerFactory.getLogger(DBUtil.class);
    //连接池
    public static ArrayList<Connection> connectionPool = new ArrayList<Connection>();

    private static final Integer amount = 5;

    private static String dbUrl;

    private static String dbDriver;

    private static String dbUsername;

    private static String dbPassword;

    @Value("${spring.datasource.url}")
    public void setUrl(String url) {
        dbUrl = url;
    }

    @Value("${spring.datasource.driver-class-name}")
    public void setDriver(String driver) {
        dbDriver = driver;
    }

    @Value("${spring.datasource.username}")
    public void setUserName(String username) {
        dbUsername = username;
    }

    @Value("${spring.datasource.password}")
    public void setPassword(String password) {
        dbPassword = password;
    }

    /**
     * 创建连接池
     */
    public static void initPool(){
        String dbType = DBHelper.getDbType(dbUrl).toUpperCase();
        logger.info("JDBC Info: [DB]=" + dbType + ";[User]=" + dbUsername + ";[Password]=" + DESUtil.getInstance().encrypt(dbPassword) + ";[Driver]=" + dbDriver + ";[Url]:" + dbUrl);
        try {
            Class.forName(dbDriver);
            for (int i = 0; i < amount; i++) {
                Connection con = DriverManager.getConnection(dbUrl,dbUsername,dbPassword);
                connectionPool.add(con);
            }
            logger.info("Get JDBC connection succeed, Pool's max connect amount is " + amount);
        } catch (ClassNotFoundException e) {
            logger.error("DB[" + dbType + "] Driver no exist!");
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     * @throws Exception
     */
    public synchronized static Connection getConnection() throws Exception{
        Connection con = null;
        if(connectionPool.size() > 0){
            con = connectionPool.get(0);
            connectionPool.remove(0);
        }else {
            throw new Exception("Connection Pool is null, please wait.");
        }
        return con;
    }

    /**
     * 放回连接
     * @param connection
     */
    public static void close(Connection connection){
        connectionPool.add(connection);
    }

    /**
     * 通用操作,查询
     * @param sql
     * @param p
     * @return
     */
    public static ResultSet query(String sql, Object...p){
        Connection con = null;
        ResultSet rs = null;
        try {
            con = getConnection();
            PreparedStatement pre = con.prepareStatement(sql);
            for (int i = 0, len = p.length; i < len; i++) {
                pre.setObject(i+1, p[i]);
            }
            rs = pre.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            close(con);
        }
        return rs;
    }


    /**
     * 通用操作,增/删/改
     * @param sql
     * @param p
     * @return
     */
    public static int ZSG(String sql,Object...p){
        int n = 0;
        Connection con=null;
        try {
            con = getConnection();
            PreparedStatement pre = con.prepareStatement(sql);
            for (int i = 0, len = p.length; i < len; i++) {
                pre.setObject(i+1, p[i]);
            }
            n = pre.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            close(con);
        }
        return n;
    }
}
